package messageMeClient.view;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import javax.swing.JLabel;

import messageMeTransfer.connection.ClientConnection;
import messageMeTransfer.packages.CommandPackage;
import messageMeTransfer.utilities.PackageWrapper;
import messageMeUtility.commands.CommandLogin;
import messageMeUtility.user.StandardUser;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class LoginDialog extends JFrame {

	private JPanel contentPane;
	private JTextField textFieldUsername;
	private JPasswordField passwordField;

	private ClientConnection connection = null;
	private PackageWrapper packageWrapper = null;

	public LoginDialog(ClientConnection connection, PackageWrapper wrapper) {
		this.connection = connection;
		this.packageWrapper = wrapper;

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 252, 141);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		textFieldUsername = new JTextField();
		textFieldUsername.setBounds(132, 11, 94, 20);
		contentPane.add(textFieldUsername);
		textFieldUsername.setColumns(10);

		JButton btnLogin = new JButton("Login!");
		btnLogin.addActionListener(this.getLoginListener());
		btnLogin.setBounds(137, 69, 89, 23);
		contentPane.add(btnLogin);

		passwordField = new JPasswordField();
		passwordField.setBounds(132, 42, 94, 20);
		contentPane.add(passwordField);

		JLabel lblNewLabel = new JLabel("Username");
		lblNewLabel.setBounds(10, 14, 112, 14);
		contentPane.add(lblNewLabel);

		JLabel lblPasswort = new JLabel("Password");
		lblPasswort.setBounds(10, 45, 112, 14);
		contentPane.add(lblPasswort);
	}

	private ActionListener getLoginListener() {
		return new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				LoginDialog.this.login();
			}
		};
	}

	private void login() {
		StandardUser user = new StandardUser(this.textFieldUsername.getText(),
				"", this.convertToString(this.passwordField.getPassword()));

		CommandLogin cLogin = new CommandLogin(user);
		CommandPackage cPackage = this.packageWrapper.wrapPackage(cLogin);
		this.connection.send(cPackage);
	}

	private String convertToString(char[] charArray) {
		String result = "";

		for (int index = 0; index < charArray.length; index++) {
			result += charArray[index];
		}
		return result;
	}
}
